﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using AvalonDock;
using RiskMan.DataClass.Models.NotBasModels;
using System.Windows.Threading;
using TheControllerRisk.Settings;
using System.Reflection;
using System.Collections.ObjectModel;
using RiskMan.Views.Dialogs;

namespace RiskMan.Views.Ledder
{
    /// <summary>
    /// Логика взаимодействия для Ledder.xaml
    /// </summary>
    public partial class Ledder : DocumentContent
    {
        private MainWindow mainWindow;
        private DispatcherTimer _dsTimer = new DispatcherTimer();

        public Ledder()
        {
            mainWindow = RiskMan.MainWindow.StaticLedder;

            InitializeComponent();

            //dtgdOrders.ItemsSource = mainWindow._dataProvider.LedderItems[i].TradeList;
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < mainWindow._dataProvider.LedderItems.Count; i++)
            {
                if (mainWindow._dataProvider.LedderItems[i].Check == true)
                {
                    mainWindow._dataProvider.LedderItems[i].isRun = false;
                }
            }
            dtgdLedder.ItemsSource = mainWindow._dataProvider.LedderItems;
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < mainWindow._dataProvider.LedderItems.Count; i++)
            {
                if (mainWindow._dataProvider.LedderItems[i].Check == true)
                {
                    if (mainWindow._dataProvider.LedderItems[i].isRun == false)
                    {

                        mainWindow._dataProvider.LedderItems[i].isRun = true;
                    }
                }
            }

            dtgdLedder.ItemsSource = mainWindow._dataProvider.LedderItems;
        }

        private void Button_AddRow_Click(object sender, RoutedEventArgs e)
        {
            LedderItem item = new LedderItem();
            newLedder nrmi = new newLedder(item, mainWindow._dataProvider, false);
            nrmi.ShowDialog();

            if (item.Account != null)
                mainWindow._dataProvider.LedderItems.Add(item);

            Update();
            cfg.SetLog("Добавлена новая блока лесенка", mainWindow.ListBox_Logs, GetType(), MethodBase.GetCurrentMethod());
        }

        /// Удаление 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            for (int j = 0; j < mainWindow._dataProvider.LedderItems.Count; j++)
            {
                if (mainWindow._dataProvider.LedderItems[j].Check == true)
                {
                    mainWindow._dataProvider.LedderItems.RemoveAt(j);
                    j--;
                }
            }

            dtgdLedder.ItemsSource = mainWindow._dataProvider.LedderItems;
        }


        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (dtgdLedder.SelectedItems.Count == 1)
            {
                int index = dtgdLedder.SelectedIndex + 1;
                //dtgdLevel.UnselectAll();
                try
                {
                    if (new DialogOkCancel("Вы действительно хотите скопировать строку " + index + "?", "Внимание").Result == MessageBoxResult.OK)
                    {
                        foreach (var item in mainWindow._dataProvider.LedderItems)
                        {
                            if (item.GuidLedder == ((LedderItem)(dtgdLedder.SelectedItem)).GuidLedder)
                            {
                                var tmp = (LedderItem)cfg.DeepClone(mainWindow._dataProvider.LedderItems[index - 1 < 0 ? 0 : index - 1]);
                                tmp.TradeList.Clear();
                                tmp.isRun = false;
                                tmp.GuidLedder = Guid.NewGuid();
                                mainWindow._dataProvider.LedderItems.Add(tmp);
                            }
                        }

                    }
                }
                catch
                { }
            }


        }

        private void DataGrid_Ledder_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            for (int i = 0; i < mainWindow._dataProvider.LedderItems.Count; i++)
            {
                if (((DataGrid)sender).SelectedIndex == i)
                    dtgdOrders.ItemsSource = mainWindow._dataProvider.LedderItems[i].TradeList;
            }


        }

        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < mainWindow._dataProvider.LedderItems.Count; i++)
            {
                mainWindow._dataProvider.LedderItems[i].Check = (sender as CheckBox).IsChecked.Value;
            }
            dtgdLedder.ItemsSource = mainWindow._dataProvider.LedderItems;
        }


        private void LedderLayout_Loaded(object sender, RoutedEventArgs e)
        {
            this.Update();

            _dsTimer.Interval = TimeSpan.FromMilliseconds(1000);
            _dsTimer.Start();
            _dsTimer.Tick += new EventHandler(_dsTimer_Tick);
        }

        public void _dsTimer_Tick(Object sender, EventArgs args)
        {
            bool running = false;
            //количество транзакций
            bool transaction = false;

            if (mainWindow.Terminals == null)
            {
                running = false;


            }
            else
            {
                if (mainWindow.Terminals.CountConnected() > 0)
                    running = true;
                else
                    running = false;
            }

            button3.IsEnabled = running;
            button4.IsEnabled = running;



            if (running == true && transaction == false)
            {
                if (mainWindow._dataProvider.LedderItems.Count > 0)
                {
                    foreach (var item in mainWindow._dataProvider.LedderItems)
                    {
                        if (item.isRun == true)
                        {
                            LedderLogik logik = new LedderLogik(mainWindow, this);
                            logik.Start(item);
                        }
                    }

                }
            }
        }

        #region обновление контектста у DataGrid

        public void Update()
        {
            dtgdLedder.CanUserAddRows = true;

            //mainWindow._dataProvider.LedderItems = this.GetUpdate(mainWindow._dataProvider.LedderItems);
            dtgdLedder.ItemsSource = mainWindow._dataProvider.LedderItems;
            //dataGrid1.ItemsSource = mainWindow._dataProvider.ACLimiteItems;
            dtgdLedder.CanUserAddRows = false;
        }

        private void DataGrid_Ledder_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (dtgdLedder.SelectedIndex >= 0)
            {
                LedderItem ldItem = ((DataGrid)sender).SelectedItem as LedderItem;
                newLedder nri = new newLedder(ldItem, mainWindow._dataProvider, true);
                nri.ShowDialog();
            }
        }

        private void DataGrid_Ledder_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            if ((sender as System.Windows.Controls.DataGrid).SelectedItems.Count == 1)
            {
                int index = (sender as System.Windows.Controls.DataGrid).SelectedIndex + 1;
                dtgdLedder.UnselectAll();
                if (new DialogYesNo("Вы действительно хотите скопировать строку " + index + "?", "Внимаение").Result == MessageBoxResult.Yes)
                {
                    var tmp = (LedderItem)cfg.DeepClone(mainWindow._dataProvider.LedderItems[index - 1 < 0 ? 0 : index - 1]);
                    if (tmp.isRun == false)
                        mainWindow._dataProvider.LedderItems.Add(tmp);
                    else
                        new DialogOkCancel("Для продолжения копирования нужно остановить копируемю строку", "Ошибка");
                }
            }
        }

        private void DataGrid_Ledder_MouseUp(object sender, MouseButtonEventArgs e)
        {
            //if ((sender as DataGrid).SelectedItems.Count == 1)
            //{
            //    bool tr = mainWindow._dataProvider.LedderItems[(sender as DataGrid).SelectedIndex].Check == true ? false : true;
            //    mainWindow._dataProvider.LedderItems[(sender as DataGrid).SelectedIndex].Check = tr;
            //}
            //dtgdLedder.ItemsSource = mainWindow._dataProvider.LedderItems;
            //dtgdLedder.Items.Refresh();
        }

        //удаление сделок по указанному инструменту, инструментам
        private void button5_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string classcode;
                for (int j = 0; j < mainWindow._dataProvider.LedderItems.Count; j++)
                {
                    if (mainWindow._dataProvider.LedderItems[j].Check == true)
                    {
                        foreach (var item in mainWindow._dataProvider.LedderItems[j].TradeList)
                        {
                            if (Properties.Settings.Default.timeLastTransaction != "")
                                if (Convert.ToDateTime(Properties.Settings.Default.timeLastTransaction).TimeOfDay + new TimeSpan(0, 0, 1) >= DateTime.Now.TimeOfDay && Convert.ToDateTime(Properties.Settings.Default.timeLastTransaction).Date == DateTime.Now.Date)
                                    if (Properties.Settings.Default.tmpTransactionInTheSeconds >= Properties.Settings.Default.TransactionInTheSeconds)
                                        System.Threading.Thread.Sleep(1000);


                            classcode = mainWindow._dataProvider.GetClasscode(mainWindow._dataProvider.LedderItems[j].Instrument);
                            if (item.OpenStatusOrder == cfg.ACTIVE)
                                mainWindow.Terminals.CancelOrder(item.OpenNumberOrder, mainWindow._dataProvider.LedderItems[j].Instrument, classcode, mainWindow._dataProvider.LedderItems[j].Account, mainWindow._dataProvider.LedderItems[j].ClientCode);
                            if (item.CloseStatusOrder == cfg.ACTIVE)
                                mainWindow.Terminals.CancelOrder(item.CloseNumberOrder, mainWindow._dataProvider.LedderItems[j].Instrument, classcode, mainWindow._dataProvider.LedderItems[j].Account, mainWindow._dataProvider.LedderItems[j].ClientCode);

                            
                        }

                        mainWindow._dataProvider.LedderItems[j].StaticsticItem.AmountDeals = 0;
                        mainWindow._dataProvider.LedderItems[j].StaticsticItem.AmountProfit = 0;
                        mainWindow._dataProvider.LedderItems[j].StaticsticItem.DateStartTrade = new DateTime(1,1,1) ;
                        mainWindow._dataProvider.LedderItems[j].StaticsticItem.MiddlePriceClose = 0;
                        mainWindow._dataProvider.LedderItems[j].StaticsticItem.MiddlePriceOpen = 0;
                        mainWindow._dataProvider.LedderItems[j].StaticsticItem.VolClose = 0;
                        mainWindow._dataProvider.LedderItems[j].StaticsticItem.VolOpen = 0;
                        mainWindow._dataProvider.LedderItems[j].TradeList.Clear();
                    }
                }
            }
            catch { }
            finally
            {
                for (int j = 0; j < mainWindow._dataProvider.LedderItems.Count; j++)
                {
                    if (mainWindow._dataProvider.LedderItems[j].Check == true)
                        mainWindow._dataProvider.LedderItems[j].TradeList.Clear();
                }
                dtgdLedder.ItemsSource = mainWindow._dataProvider.LedderItems;
            }
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {

        }

        #endregion

    }
}
